package zip;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 根据svn的change log，生成PSA与ESS的hotfix目录及文件
 * <p>
 * 方法1
 * 1 在项目右键属性Team-显示资源历史记录中找到需要生成hotfix的记录
 * 2 选中记录后点右键-Generate ChangeLog，选择svn log with affected paths
 * 3 将生成的日志文件拷贝到/svnlog/svnlog.log中
 * 4 在main方法中设置本机上psa和ess在tomcat中的目录basePsa和baseEss，输出目录desFolder
 * 5 运行
 * 6 使用生成的文件打包
 * <p>
 * 方法2
 * 1 在日志文件填写需要生成hotfix的文件相对路径，文件路径必须以M /CLOUD/PSA，A /CLOUD/PSA，M /CLOUD/ESS，A /CLOUD/ESS开头（M A为svn中的修改状态）
 * 如 M /CLOUD/PSA/src/main/webapp/cm/jsp/apinvoice/invoicePaymentInquery.jsp
 * 或 A /CLOUD/PSA/src/main/java/cn/com/norming/pr/web/dataImport/allocationsetimport/ImportAllocationset.java
 * 其中PSA_PERFIX ,ESS_PERFIX可以修改为自己的项目文件名。
 * 2 在main方法中设置本机上psa和ess在tomcat中的目录basePsa和baseEss，输出目录desFolder
 * 3 运行
 * 4 使用生成的文件打包
 *
 * @author tobin
 */
public class PackBase {

    private static String FLAG_MODIFY = "M";
    private static String FLAG_ADD = "A";
    private static String FLAG_DELETE = "D";

    private static String PSA_PERFIX = "/xx";//如不使用svnlog，可以修改为自己的项目文件名。
    private static String PROJECT_PERFIX = "/branches/sharing-center-server/sharing-center-server-beta";//如不使用svnlog，可以修改为自己的项目文件名。
    private static String JAVA_SUFFIX = ".java";
    private static String CLASS_SUFFIX = ".class";
    private static String DASH = "/";

    private static String SRC_MAIN_JAVA = "/base_src";
    private static String[] SRC_MAIN_JAVAS = new String[]{};
    private static String[] SRC_MAIN_JAVASs = {"at_src",
            "at_src_cfg",
            "base_src",
            "base_src_cfg",
            "base_src_design",
            "base_src_test",
            "bf_src",
            "bf_src_cfg",
            "bi_src",
            "bi_src_cfg",
            "ci_src",
            "ci_src_cfg",
            "cm_src",
            "cm_src_cfg",
            "customized_src",
            "er_src",
            "er_src_cfg",
            "ess_cfg",
            "fm_src",
            "fm_src_cfg",
            "hr_src",
            "hr_src_cfg",
            "it_src",
            "it_src_cfg",
            "ln_src",
            "ln_src_cfg",
            "lv_src",
            "lv_src_cfg",
            "md_src",
            "md_src_cfg",
            "oa_src",
            "oa_src_cfg",
            "pa_src",
            "pa_src_cfg",
            "paxy_src",
            "paxy_src_cfg",
            "pm_src",
            "pm_src_cfg",
            "po_src",
            "po_src_cfg",
            "pp_src",
            "pp_src_cfg",
            "pr_src",
            "pr_src_cfg",
            "psa_cfg",
            "rc_src",
            "rc_src_cfg",
            "rm_src",
            "rm_src_cfg",
            "ss_src",
            "st_src",
            "st_src_cfg",
            "tr_src",
            "tr_src_cfg",
            "ts_src",
            "ts_src_cfg",
            "ts_src_design",
            "yw_src",
            "yw_src_cfg"};


    private static String SRC_MAIN_RESOURCES = "/src/main/resources";
//    private static String SRC_MAIN_WEBAPP = "/src/main/webapp";
    private static String SRC_MAIN_WEBAPP = "/WebRoot";

    private static String DES_MAIN_JAVA = "/WEB-INF/classes";
    private static String DES_MAIN_JAVA_ = "WEB-INF/classes";
    private static String DES_MAIN_RESOURCES = "/WEB-INF/classes";
    private static String DES_MAIN_WEBAPP = "";

    private static String FOLDER_PSA = "psa_cpa";
    private static String FOLDER_ESS = "ess_cpa";

    public static LinkedList<String> parser(String fileAddr) {
        File logFile = new File(fileAddr);
        LinkedList<String> filePaths = new LinkedList<String>();
        LinkedList<String> filePathToVerify = new LinkedList<String>();
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(logFile));
            String temp = reader.readLine();
            while (temp != null) {
                if (temp.contains(PSA_PERFIX)) {
                    int startIndex = temp.indexOf(PSA_PERFIX);
                    String perfix = temp.substring(0, startIndex);
                    if (perfix.contains(FLAG_MODIFY) || perfix.contains(FLAG_ADD)) {
                        // 地址以M或者A开头，不处理D开头地址
                        filePaths.add(temp.substring(startIndex, temp.length()));
                    } else {
                        filePathToVerify.add(temp);
                    }
                } else if (temp.contains(PROJECT_PERFIX)) {
                    int startIndex = temp.indexOf(PROJECT_PERFIX);
                    String perfix = temp.substring(0, startIndex);
                    if (perfix.contains(FLAG_MODIFY) || perfix.contains(FLAG_DELETE) || perfix.contains(FLAG_ADD)) {
                        filePaths.add(temp.substring(startIndex, temp.length()));
                    } else {
                        filePathToVerify.add(temp);
                    }
                }
//				System.out.println(temp);
                temp = reader.readLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (String t : filePathToVerify) {
            System.out.println("未处理：" + t);
        }
        return filePaths;
    }


    public static void copyFiles(LinkedList<String> filePaths, String srcFolderPsa, String srcFolderEss, String desFolder) {
        //清理
        File psaRoot = new File(desFolder + "/" + FOLDER_PSA);
        if (psaRoot.exists()) {
            FileHelper.deleteDir(psaRoot);
            psaRoot.delete();
        }
        File essRoot = new File(desFolder + "/" + FOLDER_ESS);
        if (essRoot.exists()) {
            FileHelper.deleteDir(essRoot);
            essRoot.delete();
        }
        //拷贝
        for (String filePath : filePaths) {
            String filePathFolder = filePath.substring(0, filePath.lastIndexOf(DASH) + 1);
            String name = filePath.substring(filePath.lastIndexOf(DASH) + 1, filePath.length());
            if (name.endsWith(JAVA_SUFFIX)) {
                //java文件，需要拷贝class
                if (filePath.contains(PSA_PERFIX)) {
                    filePathFolder = filePathFolder.replace(PSA_PERFIX, "");
                    filePathFolder = filePathFolder.replace(SRC_MAIN_JAVA, DES_MAIN_JAVA);
                    for (int i = 0; i < SRC_MAIN_JAVAS.length; i++) {
                        filePathFolder = filePathFolder.replace(SRC_MAIN_JAVAS[i], DES_MAIN_JAVA_);
                    }
                    filePathFolder = filePathFolder.replace(SRC_MAIN_RESOURCES, DES_MAIN_RESOURCES);
                    filePathFolder = filePathFolder.replace(SRC_MAIN_WEBAPP, DES_MAIN_WEBAPP);
                    final String finalName = name.replace(JAVA_SUFFIX, "");
                    String oldPath = srcFolderPsa + filePathFolder + finalName + CLASS_SUFFIX;
                    String newPath = desFolder + "/" + FOLDER_PSA + filePathFolder + finalName + CLASS_SUFFIX;
                    System.out.println("---->" + newPath);
                    FileHelper.copyFile(oldPath, newPath);
                    //拷贝内部类
                    File oldFolder = new File(srcFolderPsa + filePathFolder);
                    String[] files = oldFolder.list(new FilenameFilter() {
                        public boolean accept(File file, String filename) {
                            return filename.startsWith(finalName + "$") && filename.endsWith(CLASS_SUFFIX) ? true : false;
                        }
                    });
                    for (String file : files) {
                        oldPath = srcFolderPsa + filePathFolder + file;
                        newPath = desFolder + "/" + FOLDER_PSA + filePathFolder + file;
                        System.out.println("---->" + newPath);
                        FileHelper.copyFile(oldPath, newPath);
                    }
                } else if (filePath.contains(PROJECT_PERFIX)) {
                    filePathFolder = filePathFolder.replace(PROJECT_PERFIX, "");
                    filePathFolder = filePathFolder.replace(SRC_MAIN_JAVA, DES_MAIN_JAVA);
                    for (int i = 0; i < SRC_MAIN_JAVAS.length; i++) {
                        filePathFolder = filePathFolder.replace(SRC_MAIN_JAVAS[i], DES_MAIN_JAVA_);
                    }
                    filePathFolder = filePathFolder.replace(SRC_MAIN_RESOURCES, DES_MAIN_RESOURCES);
                    filePathFolder = filePathFolder.replace(SRC_MAIN_WEBAPP, DES_MAIN_WEBAPP);
                    final String finalName = name.replace(JAVA_SUFFIX, "");
                    String oldPath = srcFolderEss + filePathFolder + finalName + CLASS_SUFFIX;
                    String newPath = desFolder + "/" + FOLDER_ESS + filePathFolder + finalName + CLASS_SUFFIX;
                    System.out.println("---->" + newPath);
                    FileHelper.copyFile(parsePacht(oldPath), parsePacht(newPath));
                    //拷贝内部类
                    File oldFolder = new File(srcFolderEss + filePathFolder);
                    String[] files = oldFolder.list(new FilenameFilter() {
                        public boolean accept(File file, String filename) {
                            return filename.startsWith(finalName + "$") && filename.endsWith(CLASS_SUFFIX) ? true : false;
                        }
                    });
                    for (String file : files) {
                        oldPath = srcFolderEss + filePathFolder + file;
                        newPath = desFolder + "/" + FOLDER_ESS + filePathFolder + file;
                        System.out.println("---->" + newPath);
                        FileHelper.copyFile(parsePacht(oldPath), parsePacht(newPath));
                    }
                }
            } else {
                //非java文件，直接拷贝
                if (filePath.contains(PSA_PERFIX)) {
                    filePathFolder = filePathFolder.replace(PSA_PERFIX, "");
                    filePathFolder = filePathFolder.replace(SRC_MAIN_JAVA, DES_MAIN_JAVA);
                    filePathFolder = filePathFolder.replace(SRC_MAIN_RESOURCES, DES_MAIN_RESOURCES);
                    filePathFolder = filePathFolder.replace(SRC_MAIN_WEBAPP, DES_MAIN_WEBAPP);
                    String oldPath = srcFolderPsa + filePathFolder + name;
                    String newPath = desFolder + "/" + FOLDER_PSA + filePathFolder + name;
                    System.out.println("---->" + newPath);
                    FileHelper.copyFile(oldPath, newPath);
                } else if (filePath.contains(PROJECT_PERFIX)) {
                    filePathFolder = filePathFolder.replace(PROJECT_PERFIX, "");
                    filePathFolder = filePathFolder.replace(SRC_MAIN_JAVA, DES_MAIN_JAVA);
                    for (int i = 0; i < SRC_MAIN_JAVAS.length; i++) {
                        filePathFolder = filePathFolder.replace(SRC_MAIN_JAVAS[i], DES_MAIN_JAVA_);
                    }
                    filePathFolder = filePathFolder.replace(SRC_MAIN_RESOURCES, DES_MAIN_RESOURCES);
                    filePathFolder = filePathFolder.replace(SRC_MAIN_WEBAPP, DES_MAIN_WEBAPP);
                    filePathFolder = filePathFolder.replace("classes_cfg", "classes");
                    String oldPath = srcFolderEss + filePathFolder + name;
                    String newPath = desFolder + "/" + FOLDER_ESS + filePathFolder + name;
//                    System.out.println(oldPath);
//                    System.out.println("---->" + newPath);
//                    System.out.println(parsePacht(oldPath));
                    System.out.println("---->" + parsePacht(newPath));
                    FileHelper.copyFile(parsePacht(oldPath), parsePacht(newPath));
                }
            }
        }
    }

    private static String parsePacht(String patch) {
        if (!File.separator.equals("/")) {
            return patch.replaceAll("/", "\\\\");
        }
        return patch;
    }
//
//    public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
//        getSrcPatch();
//        String base = "D:\\xyzh\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\";
//        String psaBase = base + "tmp1\\wtpwebapps\\ess_cpa";
//        String essBase = base + "tmp1\\wtpwebapps\\ess_cpa";
//        String desFolder = "D:\\xyzh\\package\\1";
//        String log = "./config/svnlog.log";
//        LinkedList<String> filePaths = SvnLogParser.parser(log);
//        SvnLogParser.copyFiles(filePaths, "", essBase, desFolder);
//    }

    public static void getSrcPatch() throws ParserConfigurationException, IOException, SAXException {
        //创建一个DOM解析器工厂对象;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        //通过工厂对象创建DOM解析器
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        //解析文档
//        InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("com\\first\\person.xml");
        InputStream inputStream = new FileInputStream(new File("./config/SRCClassPatch.xml"));
        Document document = documentBuilder.parse(inputStream);//doc 即为树状结构的存储对象,在内存中;

        List<String> srcList = new ArrayList<String>();

        NodeList classpathentry = document.getElementsByTagName("classpathentry");
        for (int i = 0; i < classpathentry.getLength(); i++) {
            if ("src".equals(classpathentry.item(i).getAttributes().getNamedItem("kind").getNodeValue())) {
                srcList.add(classpathentry.item(i).getAttributes().getNamedItem("path").getNodeValue());
            }
        }
        SRC_MAIN_JAVAS = srcList.toArray(new String[srcList.size()]);
        System.out.println(SRC_MAIN_JAVAS);

    }
    public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
        getSrcPatch();
        InputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(new File("./config/path.properties"));
            Properties properties = new Properties();
            properties.load(fileInputStream);

            String essBase = properties.getProperty("ess_cpa_tomcat_path");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH：mm：ss");
            String desFolder = properties.getProperty("out_hotfix_path")+"\\"+simpleDateFormat.format(new Date());
            String log = "./config/svnlog.log";
            if (!new File(essBase).exists()) {
                System.out.println("ess_cpa目录不存在");
                return;
            }
            if (!new File(desFolder).exists()) {
                new File(desFolder).mkdirs();
            }
            LinkedList<String> filePaths = PackBase.parser(log);
            PackBase.copyFiles(filePaths, "", essBase, desFolder);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}

